package com.zhuangjie.shop.service.impl;

import com.zhaungjie.base.utils.ArraySerializeForDB;
import com.zhuangjie.shop.entity.DishFlavor;
import com.zhuangjie.shop.mapper.DishFlavorMapper;
import com.zhuangjie.shop.service.DishFlavorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhuangjie.shop.helper.ShopModuleTokenDataProvider;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜品口味表 服务实现类
 * </p>
 *
 * @author zhuangjie
 * @since 2023-09-24
 */
@Service
public class DishFlavorServiceImpl extends ServiceImpl<DishFlavorMapper, DishFlavor> implements DishFlavorService {

    @Override
    public List<DishFlavor> selectShopDishFlavor(String keyword, Integer max) {
        // 只查询关联店铺的所有
        List<DishFlavor> dishFlavorList = this.baseMapper.selectShopDishFlavor(ShopModuleTokenDataProvider.getShopId(),keyword,Integer.MAX_VALUE);
        Map<String, DishFlavor> flavorMap = new HashMap<>();
        // 冲突项value值合并
        for (DishFlavor dishFlavor : dishFlavorList) {
            DishFlavor inMapEqualsDish = flavorMap.get(dishFlavor.getName());
            if (inMapEqualsDish != null) {
                List<String> dishFlavorValues = ArraySerializeForDB.deserialize(inMapEqualsDish.getValue(), dishFlavor.getValue());
                // 去重
                dishFlavorValues = dishFlavorValues.stream().distinct().collect(Collectors.toList());
                String dishFlavorValuesSerialize = ArraySerializeForDB.serialize(dishFlavorValues);
                inMapEqualsDish.setValue(dishFlavorValuesSerialize);
            }else {
                flavorMap.put(dishFlavor.getName(),dishFlavor);
            }
        }
        return new ArrayList<>(flavorMap.values());
    }
}
